#! /bin/sh
# Read yaal/LICENSE.md file for copyright and licensing information.

dirRoot=""
dirPrefix=""

for arg in "${@}" ; do
	case ${arg} in
		--dir-root=*)    dirRoot="$(echo ${arg} | sed 's;--dir-root=;;')" ;;
		--dir-prefix=*)  dirPrefix="$(echo ${arg} | sed 's;--dir-prefix=;;')" ;;
		*)
			echo "unknown option: ${arg}"
			exit 1
		;;
	esac
done

if [ -z "${dirRoot}" -o -z "${dirPrefix}" ] ; then
	printf "%b\n" "Core settings not found!"
	exit 1
fi

line="$(grep -s LD_LIBRARY_PATH ${HOME}/.profile ${HOME}/.bashrc ${HOME}/.bash_profile ${HOME}/.cshrc ${HOME}/.tcshrc ${HOME}/.login ${HOME}/.zshrc ${HOME}/.zlogin ${HOME}/.zshenv ${HOME}/.zsh/zlogin ${HOME}/.zsh/zshrc ${HOME}/.zsh/zshenv)"
if [ "x$line" != "x" ] ; then
	printf "%b\n" "Environment have been already set."
	exit 1
fi

yaalPrefix=`echo ${dirPrefix} | sed -e 's/\//\\\\\//g'`

shell_env() {
	cat "${dirRoot}/_aux/${1}" | sed -e "s/{YAAL_PREFIX}/${yaalPrefix}/g"
	cat "${dirRoot}/_aux/set-limits.sh"
}

printf "%b\n" "Compilation have been finished !"
printf "%b\n" "It is need to be added several lines to your .SHELLrc file :"
printf "%b\n" "#v+"
shell_env shellrc
printf "%b\n" "#v-"
printf "%b\n" "or for C shell :"
printf "%b\n" "#v+"
shell_env shellrc.csh
printf "%b\n" "#v-"
printf "%b" "Do it now ? (yes/[no]) "
read answer
if [ -f yaalrc ] ; then
	cd _aux
fi
if [ "$answer" ] ; then
	if [ $answer = "yes" ] ; then
		user="$(whoami)"
		shell="$(grep $user /etc/passwd | tr \/ '\n'|tail -1)"
		case "${shell}" in
			sh)
				shell_env shellrc >> "${HOME}/.profile"
			;;
			zsh)
				if [ -f "${HOME}/.zsh/zshrc" ] ; then
					shell_env shellrc >> "${HOME}/.zsh/zshrc"
				elif [ -f "${HOME}/.zshrc" ] ; then
					shell_env shellrc >> "${HOME}/.zshrc"
				fi
			;;
			bash)
				shell_env shellrc >> "${HOME}/.bashrc"
			;;
			csh)
				shell_env shellrc.csh >> "${HOME}/.cshrc"
			;;
			tcsh)
				shell_env shellrc.csh >> "${HOME}/.tcshrc"
			;;
		esac
	else
		printf "%b\n" "Remember to add this lines so that libraries could work properly"
	fi
else
	printf "%b\n" "Remember to add this lines so that libraries could work properly"
fi

printf "%b\n" "Environment setup process ends."

exit 0

